import { Injectable } from '@nestjs/common';
import { PrismaService } from '../db/prisma.service';
import { Good, Prisma } from '@prisma/client';
import { requestPromise } from 'src/interface';

@Injectable()
export class GoodsService {
  constructor(private prisma: PrismaService) {}

  async findOne(
    goodWhereUniqueInput: Prisma.GoodWhereUniqueInput,
  ): Promise<Good | null> {
    return this.prisma.good.findUnique({
      where: {
        id: +goodWhereUniqueInput.id,
      },
    });
  }

  async findAll(params: {
    pageNum?: number;
    pageSize?: number;
    cursor?: Prisma.GoodWhereUniqueInput;
    goodName?: string;
    supplierId?: number;
    cateId?: number;
    orderBy?: Prisma.GoodOrderByWithRelationInput;
  }): Promise<requestPromise> {
    const {
      pageNum = 1,
      pageSize = 10,
      cursor,
      goodName,
      orderBy,
      cateId,
      supplierId,
    } = params;
    const totalUsersCount = await this.prisma.good.count({
      where: {
        goodName: {
          contains: goodName,
        },
        cateId,
        supplierId,
      },
    });
    const goods = await this.prisma.good.findMany({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      cursor,
      where: {
        goodName: {
          contains: goodName,
        },
        cateId,
        supplierId,

      },
      orderBy,
      include: {
        Sku: true 
      }
    });
    return {
      code: 200,
      message: 'success',
      data: {
        list: goods,
        total: totalUsersCount,
      },
    };
  }

  async create(data: any): Promise<Good> {
    console.log(data, 'data');
    try {
      const result = await this.prisma.good.create({
        data: {
          specialIds: data.specialIds,
          supplierId: data.supplierId,
          goodImg: data.goodImg,
          cateId: data.cateId,
          goodName: data.goodName,
          unitId: data.unitId,
          goodCode: data.goodCode,
          Sku: {
            create: data.Sku
          },
        },
      });
      console.log(result, 'result');
      return result;
    } catch (error) {
      console.log(error, 'error');
    }
  }

  async update(params: {
    where: Prisma.GoodWhereUniqueInput;
    data: any;
  }): Promise<Good> {
    const { where, data } = params;
  
    // 获取现有 SKU
    const existingSkus = await this.prisma.sku.findMany({
      where: { goodId: +where.id },
      select: { id: true },
    });
  
    // 分离出需要创建、更新和删除的 SKU
    let createSku = data.Sku.filter((update) => !update.id);
    let updateSku = data.Sku.filter((update) => update.id);
    let deleteSkuIds = existingSkus.filter((sku) => !data.Sku.some((newSku) => newSku.id === sku.id)).map((sku) => sku.id);
  
    // 开始事务
    return this.prisma.$transaction(async (prisma) => {
      // 删除 SKU
      if (deleteSkuIds.length > 0) {
        await prisma.sku.deleteMany({ where: { id: { in: deleteSkuIds } } });
      }
  
      // 创建 SKU
      if (createSku.length > 0) {
        await prisma.sku.createMany({
          data: createSku.map((sku) => ({
            goodId: +where.id,
            price: sku.price,
            tradePrice: sku.tradePrice,
            showPrice: sku.showPrice,
            quantity: sku.quantity,
            propertiesId: sku.propertiesId,
            propertiesName: sku.propertiesName,
            imageUrl: sku.imageUrl,
          })),
        });
      }
  
      // 更新 SKU
      if (updateSku.length > 0) {
        await Promise.all(
          updateSku.map(async (sku) => {
            await prisma.sku.update({
              where: { id: sku.id },
              data: {
                price: sku.price,
                tradePrice: sku.tradePrice,
                showPrice: sku.showPrice,
                quantity: sku.quantity,
                propertiesId: sku.propertiesId,
                propertiesName: sku.propertiesName,
                imageUrl: sku.imageUrl,
              },
            });
          })
        );
      }
  
      // 更新商品
      return prisma.good.update({
        data: {
          specialIds: data.specialIds,
          supplierId: data.supplierId,
          goodImg: data.goodImg,
          cateId: data.cateId,
          goodName: data.goodName,
          unitId: data.unitId,
          goodCode: data.goodCode,
        },
        where,
      });
    });
  }

  async delete(where: Prisma.GoodWhereUniqueInput): Promise<Good> {
    return this.prisma.good.delete({
      where: {
        id: +where.id,
      },
    });
  }
}
